<!-- src/pages/goods/goods.vue -->
<script setup lang="ts">
// 获取屏幕边界到安全区域距离
import { addCartApi, getGoodsApi } from '@/api/goods.ts'
import type { GoodsResult } from '@/types/goods'
import { computed, ref } from 'vue'
import ServicePanel from '@/pages/goods/components/ServicePanel.vue'
import AddressPanel from '@/pages/goods/components/AddressPanel.vue'
import GoodsSkeleton from '@/pages/goods/components/GoodsSkeleton.vue'
import vkDataGoodsSkuPopup from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup.vue'
import type {
  SkuPopupEvent,
  SkuPopupLocaldata,
} from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup'
import debounce from 'lodash.debounce'
import { useAddressStore, useMemberStore } from '@/stores'
import { onShareAppMessage, onShareTimeline, onShow } from '@dcloudio/uni-app'
import { getAddressListApi } from '@/api/address.ts'
import type { AddressItem } from '@/types/address'
import { unFinished } from '@/utils/unFinished.ts'

const { safeAreaInsets } = uni.getWindowInfo()

// 获取路由参数
const query = defineProps<{
  id: string
}>()

const goods = ref<GoodsResult>()
// 是否展示骨架屏
const isLoading = ref(true)
// 是否显示SKU组件
const isShowSku = ref(false)
const memberStore = useMemberStore()
// 地址列表
const addressList = ref<AddressItem[]>([])
// 待处理事件列表
const pendingList = ref<Function[]>([])
// 每次访问页面都重新请求地址数据
onShow(async () => {
  if (!memberStore.profile) return
  // 处理未完成队列，并且清空队列
  pendingList.value.forEach((fn) => fn())
  pendingList.value = []
  // 获取地址列表
  const res = await getAddressListApi()
  addressList.value = res.result || []
})
// 商品信息
const localdata = ref<SkuPopupLocaldata>({} as SkuPopupLocaldata)
const getGoods = async () => {
  const res = await getGoodsApi(query.id)
  goods.value = res.result
  // 获取地址列表
  addressList.value = res.result.userAddresses || []

  // SKU组件所需格式
  localdata.value = {
    _id: res.result.id,
    name: res.result.name,
    goods_thumb: res.result.mainPictures[0],
    // spec_list 的格式是：
    // [{
    //   "name": "颜色",
    //   "list": [
    //     { "name": "红色" },
    //     { "name": "黑色" },
    //     { "name": "白色" }
    //   ]
    // },...]
    spec_list: res.result.specs.map((specItem) => ({ name: specItem.name, list: specItem.values })),
    // sku_list 的格式是：
    // [{
    //   "_id": "001",
    //   "goods_id": "001",
    //   "goods_name": "iphone11",
    //   "image": "https://img14.360buyimg.com/n0/jfs/t1/79668/22/9987/159271/5d780915Ebf9bf3f4/6a1b2703a9ed8737.jpg",
    //   "price": 19800,
    //   "sku_name_arr": ["红色", "128G", "公开版"],
    //   "stock": 1000
    // },...]
    sku_list: res.result.skus.map((skuItem) => ({
      _id: skuItem.id,
      goods_id: res.result.id,
      goods_name: res.result.name,
      image: skuItem.picture,
      price: skuItem.price * 100, // 注意：需要乘以 100，因为 price 的单位是分，v.price 的单位是元
      stock: skuItem.inventory,
      // sku_name_arr 的格式是：["蓝色", "128G", "公开版"]
      // skuSpecItem 的格式是：{name: "颜色", valueName: "蓝色"}
      sku_name_arr: skuItem.specs.map((skuSpecItem) => skuSpecItem.valueName),
    })),
  }

  isLoading.value = false
}

getGoods()

// 当前的轮播图索引
const activeIndex = ref(0)
const onChange: UniHelper.SwiperOnChange = (e) => {
  // 最新的uniHelper更新了Swiper标签的声明类型，它把undefined去掉了，所以e.detail一定不为空
  activeIndex.value = e.detail.current
}

const onPreviewImage = () => {
  uni.previewImage({
    // 断言 mainPictures 一定存在
    // 这里一定要把所有图片都传过去，这样才能支持预览多张图片，你传一张的话只能预览一张，就不能切换了
    urls: goods.value!.mainPictures,
    current: activeIndex.value,
  })
}

const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const popupName = ref<'address' | 'service'>()

// typeof 是拿到一个值的类型
const onPopupOpen = (name: typeof popupName.value) => {
  popupName.value = name
  popup.value?.open()
}

enum skuMode {
  Both = 1,
  // 选择 SKU
  Cart = 2,
  // 购买
  Buy = 3,
}

const mode = ref<skuMode>(skuMode.Both)
const openSkuPopup = (val: skuMode) => {
  // 非空校验
  if (!Object.keys(localdata.value).length) {
    return uni.showToast({ title: '未获取到商品信息', icon: 'none' })
  }
  mode.value = val
  isShowSku.value = true
}

const skuPopupRef = ref<InstanceType<typeof vkDataGoodsSkuPopup>>()
// 计算被选中的值
const selectArrText = computed(() => {
  return skuPopupRef.value?.selectArr?.join(' ').trim() || '请选择商品规格'
})

const addCart = debounce(async (e: SkuPopupEvent) => {
  // 登录态校验逻辑（优先级：先判断用户主动登录场景）
  // 两种登录场景说明：
  // 1. 用户主动登录：通过路由跳转保留当前页面状态
  // 2. 后端401鉴权跳转：会触发页面销毁重建（需避免该情况）
  if (!memberStore.profile) {
    // 把加入购物车逻辑放入队列，待登录成功后执行
    pendingList.value.push(() => addCart(e))
    // 通过uni.navigateTo模拟主动登录行为，防止页面销毁
    return uni.navigateTo({
      url: '/pages/login/login',
    })
  }

  await addCartApi({ skuId: e._id, count: e.buy_num })

  uni.showToast({ title: '添加成功' })
  isShowSku.value = false
}, 500)

const addressStore = useAddressStore()
const selectedAddress = computed(() => {
  return addressStore.selectedAddress
})

const buyNow = (e: SkuPopupEvent) => {
  uni.navigateTo({
    url: `/pagesOrder/pages/create/create?skuId=${e._id}&count=${e.buy_num}&addressId=${selectedAddress.value?.id}`,
  })
  isShowSku.value = false
}

// 转发给朋友
onShareAppMessage(() => ({
  title: '小兔鲜商城',
  path: '/pages/goods/goods' + query.id,
}))
// 转发到朋友圈
onShareTimeline(() => ({
  query: query.id,
}))
</script>

<template>
  <!-- SKU弹窗组件 -->
  <vk-data-goods-sku-popup
    v-model="isShowSku"
    :localdata="localdata"
    :mode="mode"
    add-cart-background-color="#FFA8680"
    buy-now-background-color="#27BA9B"
    :actived-style="{
      color: '#27BA9B',
      borderColor: '#27BA9B',
      backgroundColor: '#E9F8F5',
    }"
    ref="skuPopupRef"
    @add-cart="addCart"
    @buy-now="buyNow"
  />

  <GoodsSkeleton v-if="isLoading" />
  <scroll-view
    v-show="!isLoading"
    scroll-y
    class="viewport"
    :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
  >
    <!-- 基本信息 -->
    <view class="goods">
      <!-- 商品主图 -->
      <view class="preview">
        <swiper circular autoplay :interval="3000" @change="onChange">
          <swiper-item v-for="item in goods?.mainPictures" :key="item">
            <!-- #ifdef MP-WEIXIN -->
            <image @tap="onPreviewImage" mode="aspectFill" :src="item" lazy-load />
            <!-- #endif -->
            <!-- #ifdef H5 || APP-PLUS -->
            <img @tap="onPreviewImage" :src="item" loading="lazy" alt="" />
            <!-- #endif -->
          </swiper-item>
        </swiper>
        <view class="indicator">
          <text>{{ activeIndex + 1 }}</text>
          <text class="split">/</text>
          <text>{{ goods?.mainPictures.length }}</text>
        </view>
      </view>

      <!-- 商品简介 -->
      <view class="meta">
        <view class="price">
          <text class="symbol">¥</text>
          <text class="number">{{ goods?.price }}</text>
        </view>
        <view class="name ellipsis">{{ goods?.name }}</view>
        <view class="desc">{{ goods?.desc }}</view>
      </view>

      <!-- 操作面板 -->
      <view class="action">
        <view class="item arrow" @tap="openSkuPopup(skuMode.Both)">
          <text class="label">选择</text>
          <text class="text ellipsis">{{ selectArrText }}</text>
        </view>
        <view class="item arrow" @click="onPopupOpen('address')">
          <text class="label">送至</text>
          <text class="text ellipsis"
            >{{
              selectedAddress
                ? selectedAddress.fullLocation + selectedAddress.address
                : '请选择收获地址'
            }}
          </text>
        </view>
        <view class="item arrow" @click="onPopupOpen('service')">
          <text class="label">服务</text>
          <text class="text ellipsis">无忧退 快速退款 免费包邮</text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail panel">
      <view class="title">
        <text>详情</text>
      </view>
      <view class="content">
        <view class="properties">
          <!-- 属性详情 -->
          <view class="item" v-for="item in goods?.details.properties" :key="item.name">
            <text class="label">{{ item.name }}</text>
            <text class="value">{{ item.value }}</text>
          </view>
        </view>
        <!-- 图片详情 -->
        <view class="pictures" v-for="item in goods?.details.pictures" :key="item">
          <!-- #ifdef MP-WEIXIN -->
          <image mode="widthFix" :src="item" lazy-load></image>
          <!-- #endif -->
          <!-- #ifdef H5 || APP-PLUS -->
          <img :src="item" alt="" loading="lazy" />
          <!-- #endif -->
        </view>
      </view>
    </view>

    <!-- 同类推荐 -->
    <view class="similar panel">
      <view class="title">
        <text>同类推荐</text>
      </view>
      <view class="content">
        <navigator
          v-for="item in goods?.similarProducts"
          :key="item.id"
          class="goods"
          hover-class="none"
          :url="`/pages/goods/goods?id=${item.id}`"
        >
          <!-- #ifdef MP-WEIXIN -->
          <image class="image" mode="aspectFill" :src="item.picture" lazy-load></image>
          <!-- #endif -->
          <!-- #ifdef APP-PLUS || H5 -->
          <img class="image" :src="item.picture" loading="lazy" alt="" />
          <!-- #endif -->
          <view class="name ellipsis">{{ item.name }}</view>
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ item.price }}</text>
          </view>
        </navigator>
      </view>
    </view>
  </scroll-view>

  <!-- 用户操作 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="icons">
      <button class="icons-button" @tap="unFinished">
        <text class="icon-heart"></text>
        收藏
      </button>
      <!-- #ifdef MP-WEIXIN -->
      <button class="icons-button" open-type="contact">
        <text class="icon-handset"></text>
        客服
      </button>
      <!-- #endif -->
      <navigator class="icons-button" url="/pages/cart/normal-cart">
        <text class="icon-cart"></text>
        购物车
      </navigator>
    </view>
    <view class="buttons">
      <view class="addcart" @tap="openSkuPopup(skuMode.Cart)">加入购物车</view>
      <view class="buynow" @tap="openSkuPopup(skuMode.Buy)">立即购买</view>
    </view>
  </view>

  <uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="10rpx 10rpx 0 0">
    <ServicePanel v-if="popupName === 'service'" @close="popup?.close"></ServicePanel>
    <AddressPanel
      v-else-if="popupName === 'address'"
      @close="popup?.close"
      :addressList="addressList"
    >
    </AddressPanel>
  </uni-popup>
</template>

<style lang="scss">
@import './style/goods';

/* 页面基础布局样式（生效于整个页面生命周期，包含骨架屏阶段） */
page {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 底部工具栏固定布局（始终固定在页面底部，即使在骨架屏显示时也保持布局结构） */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx var(--window-bottom);
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .buttons {
    display: flex;

    view {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 36rpx;
    }

    .addcart {
      background-color: #ffa868;
    }

    .buynow,
    .payment {
      background-color: #27ba9b;
      margin-left: 20rpx;
    }
  }

  .icons {
    padding-right: 10rpx;
    display: flex;
    align-items: center;
    flex: 1;

    .icons-button {
      flex: 1;
      text-align: center;
      line-height: 1.4;
      padding: 0;
      margin: 0;
      border-radius: 0;
      font-size: 20rpx;
      color: #333;
      background-color: #fff;
    }

    text {
      display: block;
      font-size: 34rpx;
    }
  }
}
</style>
